class Detail{
    constructor(){
     this.getGoodsId();
     this.changeName();
     this.logout()
    }

     //退出登陆
     logout(){
      this.$('.goHome').addEventListener('click',this.userLogout);
      // let res = this.$('.gohome');
      // console.log(res);
   }
    userLogout=()=>{
      // console.log(11111);
      // 发送ajax请求
      let userId = localStorage.getItem('user_id');
      console.log(userId);
      let res = axios.get('http://localhost:8888/users/logout?id='+userId).then(()=>{
         location.assign('./search.html')
         console.log(this);
      });
      // console.log(res);
   }



    //登陆后显示用户名
async changeName(){
    let userId = localStorage.getItem('user_id');
    // console.log(userId);
    axios.defaults.headers['authorization'] = 'application/x-www-form-urlencoded';
   let { status,data } = await axios.get('http://localhost:8888/users/info?id='+userId);
//    console.log(data.info.nickname);
     let username = data.info.nickname;
     if(status!=200) return
     let user = this.$('.username');
    //  console.log(user);
    let param = `${ username }<i class="iconfont icon-jiantou_xiangxia1"></i>`
     user.innerHTML = param;
     let token = localStorage.getItem('token');
    //  console.log(token);
     if(!token){
        user.innerHTML = '请登录';
        location.assign('./login.html?returnUrl=./search.html')
     }
}



    getGoodsId(){
      let arr = window.location.search;
    //   console.log(arr);
    let id = arr.split('?')[1];
    // console.log(id);
    this.getGoods(id);
    
    }
    
    //将对应数据渲染到详情页面
   async getGoods(id){
       //发送ajax请求
        let { status,data } = await axios.get('http://localhost:8888/goods/item?id='+id);
        // console.log(status,data);
        //判断服务器状态
        if(status!=200||data.code!=1) return;
        //将商品信息渲染到页面中
        let html = '';
        var arr = [];
        let info = data.info;
        // console.log(info);
        for(let i in info){
            arr.push({[i]:info[i]});
        }
        // console.log(arr);
        
        arr.forEach(() => {
            html =` <div class="jieshao mt20 w clearfix">
        <div class="left fl" style="position: relative;">
          <div class="hiddenbox">
          </div>
          <img src="${arr[2].img_big_logo}">
          <div class="smallbox"></div>
          <div class="bigbox">
            <img class="bimg" src="${arr[2].img_big_logo}">
          </div>
          <div class="swiper-container swiper-container-horizontal">
            <div class="swiper-wrapper">
              <div class="swiper-slide active">
                <img src="${arr[2].img_big_logo}"  alt="">
                <img src="${arr[2].img_big_logo}" alt="">
                <img src="${arr[2].img_big_logo}" alt="">
                <img src="${arr[2].img_big_logo}" alt="">
                <img src="${arr[2].img_big_logo}" alt="">
                <img src="${arr[2].img_big_logo}" alt="">
                <img src="${arr[2].img_big_logo}" alt="">
                <img src="${arr[2].img_big_logo}" alt="">
              </div>
            </div>
            <!-- Add Arrows -->
            <div class="swiper-button-next" style="background-color:#fff;height:100%"></div>
            <div class="swiper-button-prev swiper-button-disabled" style="background-color:#fff;height:100%"></div>
          </div>
        </div>
        <div class="right fr">
          <div class="h3 ml20 mt20">${arr[1].title}</div>
          <div class="jianjie mr40 ml20 mt10">变焦双摄，4 轴防抖 / 骁龙835 旗舰处理器，6GB 大内存，最大可选128GB 闪存 / 5.15" 护眼屏 / 四曲面玻璃/陶瓷机身</div>
          <div class="jiage ml20 mt10">${arr[3].price}</div>
          <div class="ft20 ml20 mt20">选择版本</div>
          <div class="xzbb ml20 mt10">
            <div class="banben fl">
              <a>
                <span>全网通版 6GB+64GB </span>
                <span>2499元</span>
              </a>
            </div>
            <div class="banben fr">
              <a>
                <span>全网通版 6GB+128GB</span>
                <span>2899元</span>
              </a>
            </div>
            <div class="banben fl">
              <a>
                <span>联通版 6GB+64GB </span>
                <span>2299元</span>
              </a>
            </div>
            <div class="banben fl">
              <a>
                <span>移动版 6GB+64GB </span>
                <span>2199元</span>
              </a>
            </div>
            <div class="clear"></div>
          </div>
          <div class="ft20 ml20 mt20">选择颜色</div>
          <div class="xzbb ml20 mt10">
            <div class="banben">
              <a>
                <span class="yuandian"></span>
                <span class="yanse">亮黑色</span>
              </a>
            </div>
    
          </div>
          <div class="xqxq mt20 ml20">
        <div class="top1 mt10">
          <div class="left1 fl">${arr[1].title}</div>
          <div class="right1 fr">${arr[3].price}元</div>
          <div class="clear"></div>
        </div>
        <div class="bot mt20 ft20 ftbc">总计：${arr[3].price}元</div>
      </div>
      <div class="xiadan ml20 mt20">
        <input class="jrgwc" type="button"  onclick="Detail.back()"; name="jrgwc" value="返回购物"/>
        <input class="jrgwc cart" type="button" name="jrgwc" onclick="Detail.sendCart(${ arr[0].goods_id })" value="加入购物车"/>
      </div>
    </div>`
        });
        
          //渲染到页面中
          this.$('.xiangqing').innerHTML = html;
          let smallObj = document.querySelector('.hiddenbox');

                let maskObj = document.querySelector('.smallbox');

                let bigObj = document.querySelector('.bigbox');

                let bimg = document.querySelector('.bimg');
                // console.log(bigObj, bimg);

                smallObj.onmousemove = function (e) {
                    let maxT = smallObj.offsetHeight - maskObj.offsetHeight;
                    let maxL = smallObj.offsetWidth - maskObj.offsetWidth;

                    let px = e.pageX - 150;
                    let py = e.pageY - 205;

                    let maskL = px - maskObj.offsetWidth / 2;
                    let maskT = py - maskObj.offsetHeight / 2;

                    if (maskL < 0) {
                        maskL = 0;
                    }
                    if (maskT < 0) {
                        maskT = 0;
                    }
                    if (maskL > maxL) {
                        maskL = maxL;
                    }
                    if (maskT > maxT) {
                        maskT = maxT;
                    }
                    maskObj.style.left = maskL + 'px';
                    maskObj.style.top = maskT + 'px';
                    // console.log(maskObj.style.left,maskObj.style.top);
                    let imaPosL = bigObj.offsetWidth - bimg.offsetWidth;
                    let imaPosT = bigObj.offsetHeight - bimg.offsetHeight;
                    // console.log(imaPosL, imaPosT);
                    let imgPosL = (maskL / maxL) * imaPosL;
                    let imgPosT = (maskT / maxT) * imaPosT;

                    bimg.style.left = imgPosL + 'px';
                    bimg.style.top = imgPosT + 'px';
                };
    }

    //返回原页面
    static back(){
      let arr = window.location.search;
      //   console.log(arr);
      let id = arr.split('?')[1];
      // console.log(id);
      let num = Math.ceil(id/15);
      console.log(num);
      let tion = `./search.html?${num}`
      location.assign(tion);
    }






    //添加到购物车
    static sendCart(goodsId){
        // console.log(1111);
    //判断是否有token
     let token = localStorage.getItem('token')
     if(!token)location.assign('./login.html?returnUrl=./search.html')
     
     //将商品加入购物车
     let userId = localStorage.getItem('user_id');
     let param = `id=${userId}&goodsId=${goodsId}`
    //  console.log(userId,goodsId);
     axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.common['Authorization'] = token;
    //发送ajax请求
    axios.post('http://localhost:8888/cart/add',param).then(res=>{
                //  console.log(res);
        let { status,data } = res;
        if(status!=200) return;
        if(data.code == 0) location.assign('./login.html');

        //提示下一步操作
        layer.confirm('是否去购物车结算', {
            btn: ['去','不去'], //按钮
            shade: false //不显示遮罩
        }, function(){
            location.assign('./cart.html')
        });
    })
    }

    
    
//封装获取节点的方法
$(ele){
    let res = document.querySelectorAll(ele);
    return res.length==1 ? res[0] : res;
}
}

new Detail;
